//
//  CDCameraViewController.swift
//  PDF
//
//  Created by dong chang on 2024/3/18.
//

import UIKit
import AVFoundation

class CDCameraViewController: UIViewController {

    @IBOutlet weak var baseView: UIView!
    @IBOutlet weak var autoScanBtn: UIButton!
    @IBOutlet weak var lightBtn: UIButton!
    @IBOutlet weak var typeScroller: UIScrollView!
    @IBOutlet weak var previewView: UIButton!
    @IBOutlet weak var toolsBtn: UIButton!
    
    @IBOutlet weak var bottomBar: UIView!
    
    @IBOutlet weak var takeButton: UIButton!
    @IBOutlet weak var topBar: UIView!
    @IBOutlet weak var bottomBarHeightConstraint: NSLayoutConstraint!
    var cameraManger: CDCameraManger!
    private var isAuto = false
    private var takeImages:[UIImage] = []
    
    @IBOutlet weak var autoTiplabel: UILabel!
    let iptionArr: [CDToolOption] = [.document,.idScanner,.ocr,.qrCode]

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        self.tabBarController?.hidesBottomBarWhenPushed = true
        cameraManger.cameraRun()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        bottomBarHeightConstraint.constant = UIDevice.safeAreaBottom() > 0 ? 128 : 96
        lightBtn.setImage("light_normal".image, for: .normal)
        lightBtn.setImage("light_select".image, for: .selected)

        autoScanBtn.setTitle("Auto Scan".localize(), for: .normal)
        autoScanBtn.setTitleColor(.white, for: .normal)
        autoScanBtn.titleLabel?.font = .helvBold(12)
        autoScanBtn.layer.cornerRadius = 16
        autoScanBtn.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.2)

        autoTiplabel.text = "Please aim at the file you want to scan".localize()
        autoTiplabel.textColor = UIColor(red: 1, green: 0.815, blue: 0.157, alpha: 1)
        autoTiplabel.font = UIFont(name: "Helvetica-Regular", size: 12)
        autoTiplabel.layer.cornerRadius = 15
        autoTiplabel.isHidden = true
        autoTiplabel.width += 30
        
        
        var config1 = UIButton.Configuration.plain()
//        config1.imagePadding = 4
//        config1.imagePlacement = .leading
        
        autoScanBtn.configuration = config1
        
        toolsBtn.setTitle("Tools".localize(), for: .normal)
        toolsBtn.setTitleColor(.white, for: .normal)
        toolsBtn.setTitleColor(.white, for: .highlighted)
        toolsBtn.titleLabel?.font = .regular(12)
        
        var config = UIButton.Configuration.plain()
        config.imagePlacement = .top
        config.imagePadding = 4
        toolsBtn.configuration = config
        var totalWidth: CGFloat = 0
        for i in 0..<iptionArr.count {
            let button = UIButton(type: .custom)
            button.setTitle(iptionArr[i].rawValue, for: .normal)
            button.setTitleColor(.white, for: .selected)
            button.tag = 10 + i
            button.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0.6), for: .normal)
            button.addTarget(self, action: #selector(onOptionAction), for: .touchUpInside)
            
            let font = UIFont(name: i == 0 ? "HelveticaNeue-Bold" : "HelveticaNeue-Regular", size: 16)
            button.titleLabel?.font = font
            button.isSelected = i == 0
            typeScroller.addSubview(button)

            let width = iptionArr[i].rawValue.labelWidth(height: typeScroller.height, font: UIFont.systemFont(ofSize: 16)) + 12.0
            button.frame = CGRect(x: totalWidth, y: 0, width: width, height: typeScroller.height)
            totalWidth = button.maxX + 12
        }
        typeScroller.contentSize = CGSize(width:totalWidth, height: typeScroller.height)
        previewView.layer.cornerRadius = 5
        previewView.backgroundColor = .lightGray

        cameraManger = CDCameraManger(baseView: self.baseView, isVideo: false)
        cameraManger.delegate = self

        lightBtn.isHidden = !cameraManger.device.hasTorch
    }
    
    @objc func onOptionAction(sender:  UIButton) {
        for i in 0..<iptionArr.count {
            if let button = typeScroller.viewWithTag(10 + i) as? UIButton {
                if button.tag == sender.tag {
                    button.isSelected = true
                    button.titleLabel?.font = .helvBold(16)
                    
                }else {
                    button.isSelected = false
                    button.titleLabel?.font = .regular(16)
                }
            }
        }
        
        let model = CDToolOption(rawValue: sender.currentTitle!)
        switch model {
        case .document:
            break
        case .idScanner:
            break
        case .ocr:
            break
        case .qrCode:
            break
        default:
            break
        }
    }

    @IBAction func takePhotoAction(_ sender: Any) {
        cameraManger.takePhoto()
    }
    
    @IBAction func toolsAction(_ sender: Any) {
        let tools = CDToolsViewController()
        self.present(tools, animated: true)
    }
    
    @IBAction func onPrevewImageAction(_ sender: Any) {
        cameraManger.stopTakePhoto()
        let pre = CDPreviewViewController()
        pre.previewImages = takeImages
        let nsv = CDNavigationController(rootViewController: pre)
        nsv.modalPresentationStyle = .fullScreen
        self.present(nsv, animated: true)
    }
    
    @IBAction func autoScanAction(_ sender: Any) {
        var config = UIButton.Configuration.plain()
        config.imagePadding = 4
        self.isAuto = !isAuto

        if isAuto{
            config.imagePlacement = .trailing
            autoScanBtn.backgroundColor = UIColor(red: 0.255, green: 0.443, blue: 1, alpha: 1)
            autoScanBtn.titleLabel?.font = .helvBold(12)

        } else {
            config.imagePlacement = .leading
            autoScanBtn.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.2)
        }
        self.autoScanBtn.configuration = config
        self.autoTiplabel.isHidden = !isAuto
    }
    
    @IBAction func dismissAction(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func lightAction(_ sender: Any) {
        if cameraManger.device.hasTorch {
            cameraManger.isFlashEnable = !cameraManger.isFlashEnable
            lightBtn.isSelected = cameraManger.isFlashEnable
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


extension CDCameraViewController: CDCameraMangerDelegate {
    func cameraTakePhotoDidComplete(image: UIImage?) {
        guard let image = image else {
            return
        }
        takeImages.append(image)
        previewView.setBackgroundImage(image, for: .normal)
    }
    
    func cameraTakeVideoDidComplete(videoUrl: URL?) {}
    
    func cameraScanQRDidComplete(content: String?, recoverHandle: @escaping () -> Void) {}
    
    func cameraUpdateDelayDidComplete(delay: Int, isEnd: Bool) {
        
    }
    
    
}
